﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;





namespace videoTest
{
    class fezConnect : IDisposable
    {
        Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
       
        IPEndPoint kinBot = new IPEndPoint(IPAddress.Any, 2000);

        

        // Pointer to an external unmanaged resource.
        private IntPtr handle;
        // Other managed resource this class uses.
        private Component component = new Component();
        // Track whether Dispose has been called.
        private bool disposed = false;



        public void Dispose()
        {
            this.Dispose();
            GC.SuppressFinalize(this);


        }

        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;

            }
        }

        // Use interop to call the method necessary
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code.
        // This destructor will run only if the Dispose method
        // does not get called.
        // It gives your base class the opportunity to finalize.
        // Do not provide destructors in types derived from this class.
        ~fezConnect()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of
            // readability and maintainability.
            Dispose(false);
        }



        public void start()
        {
            //*** New style of connecting to an end point. This is the same style that is implemented on windows 8 metro client
            // ** provides faster access to the network by setting the networking on a seperate thread from the GUI.
            //** Reference: http://www.silverlightshow.net/items/Implements-network-protocol-easily-with-a-generic-SocketClient.aspx
            //** Reference: http://social.msdn.microsoft.com/forums/en-us/wpdevelop/thread/36176f3b-d274-4337-9200-f4bb36318323


            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.2.200"), 2000);
            args.Completed += new EventHandler<SocketAsyncEventArgs>(Operation_Completed);
            mySocket.ConnectAsync(args);
            //this.mySocket.Bind(kinBot);
            
        }

        void Operation_Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                Console.Write("Did not connect to the KinBot " + e.LastOperation.ToString());   
            }
            else if (e.LastOperation == SocketAsyncOperation.Connect)
            {
                App.kinbotKinected = true;
                Console.Write("Connected to KinBot");
            }

        }

       

        public void sendData(string send)
        {
          
                byte[] data = Encoding.UTF8.GetBytes(send);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.2.200"),2000);

                args.SetBuffer(data, 0, data.Length);


                mySocket.SendToAsync(args);
         


           ////// int speed = 0;
           ////// string incomingMsg;
           //// while (mySocket.Poll(20000 , SelectMode.SelectRead))
           //// {
                
           ////     if (mySocket.Available > 0)
           ////     {
           ////         //headData.Text = (send);
           ////         byte[] inBuf = new byte[mySocket.Available];
           ////         EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0);
           ////         //mySocket.ReceiveFrom(inBuf, ref recEndPoint);
           ////         // fezMessage.Text = ("Message From" + ((IPEndPoint)recEndPoint).Address.ToString());
           ////         //incomingMsg = (new string(Encoding.UTF8.GetChars(inBuf)));

           ////        // byte[] toSend = BitConverter.GetBytes(speed);
                    
           ////         byte[] bytesToSend = Encoding.UTF8.GetBytes(send);

           ////         // byte[] bytesToSend = BitConverter.GetBytes(ledDimmerValue);
           ////         mySocket.SendTo(bytesToSend,bytesToSend.Length, SocketFlags.None, (IPEndPoint)recEndPoint);

           ////         //if (incomingMsg != null)
           ////         //{
           ////         //    //Not doing anything with incomingMsg, would like to eventualy get rid of it. 
           ////         //    // Have not found a good use for It.
           ////         //    // this is a message that is sent from the fez to the computer. 
           ////         //}
           ////     }

           //// }
        }



              public void sendData(byte[] send)
        {
            string incomingMsg;
            while (mySocket.Poll(200, SelectMode.SelectRead))
            {
                if (mySocket.Available > 0)
                {
                    //headData.Text = (send);
                    byte[] inBuf = new byte[mySocket.Available];
                    EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    mySocket.ReceiveFrom(inBuf, ref recEndPoint);
                    // fezMessage.Text = ("Message From" + ((IPEndPoint)recEndPoint).Address.ToString());
                    incomingMsg = (new string(Encoding.UTF8.GetChars(inBuf)));


                   

                    //byte[] bytesToSend = Encoding.UTF8.GetBytes(send);

                    // byte[] bytesToSend = BitConverter.GetBytes(ledDimmerValue);
                    mySocket.SendTo(send, send.Length, SocketFlags.None, (IPEndPoint)recEndPoint);

                    if (incomingMsg != null)
                    {
                        
                    }
                }

            }
        }
    }
}

   
